package com.zf.shuashua.ui.mine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.duoyou.task.openapi.DyAdApi;
import com.flyco.tablayout.SlidingTabLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.meis.base.mei.utils.NumberUtils;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertManager;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseFragment;
import com.zf.shuashua.bean.BannerBean;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.Me;
import com.zf.shuashua.bean.NotificationInfo;
import com.zf.shuashua.bean.Wallet;
import com.zf.shuashua.bean.advert.MistakeTimeBean;
import com.zf.shuashua.common.ScreenUtils;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.adapter.MineBannerAdapter;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.notice.MessageActivity;
import com.zf.shuashua.ui.popup.ButtleLimitPopup;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.ui.popup.WithdrawConfirmPopup;
import com.zf.shuashua.utils.CommonConstants;
import com.zf.shuashua.utils.NotificationUtil;
import com.zf.shuashua.utils.TimeUtils;
import com.zf.shuashua.utils.ToNotification;
import com.zf.shuashua.utils.UIUtils;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.bannerview.BaseViewHolder;
import com.zhpan.bannerview.constants.IndicatorGravity;
import com.zhpan.indicator.enums.IndicatorSlideMode;
import com.zhpan.indicator.enums.IndicatorStyle;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MineFragment extends BaseFragment implements View.OnClickListener {
    private static final int EDITPERSONALACTIVITY = 1;//编译个人资料
    public static final int FOCUSLISTACTIVITY = 2;//关注
    private static final int SETTINGACTIVITY = 3;//设置
    public static final int WITHDRAW = 8;//提现
    static final String EditPersonal = "EditPersonalActivity";
    private static final String LOAN_URL = "http://tgh5.rytad.com/module/fanZhou.html?operate_code=ord201117_cddsp&position_code=ads201117_cddsp";
    private String[] titles = {"喜欢", "作品"};
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private MyPagerAdapter adapter;
    private ImageView imgAvatar;
    private TextView tvName;
    private ImageView imgEdit;
    private TextView tvFocus;
    private TextView tvFans;
    private TextView tvZan;
    private TextView tvSign;
    private TextView tvMyWing;
    private TextView tvMoney;
    private TextView tvLogin;
    private TextView tvNoticeOpen;
    private LinearLayout llFocus;
    private LinearLayout llFans;
    private LinearLayout llZan;
    private LinearLayout llWallet;
    private LinearLayout llWing;
    private LinearLayout llNotice;
    private LinearLayout llNoticeClose;
    private ImageView imgInviteFriends;
    private ImageView imgSetting;
    private ViewPager vp;
    private SlidingTabLayout tabLayout;
    private Me.DataBean data = new Me.DataBean();
    private MineFragmVM VM;
//    private MineLikeVideoFragment likeVideoFragment;
//    private MineListVideoFragment listVideoFragment;

    private ImageView imgUnread;
    //用户已经关闭推送提醒view，本次登录不再弹出
    private boolean hasNoticeClose;

    private BannerViewPager<BannerBean, BaseViewHolder<BannerBean>> bannerView;

    @Override
    public void initViewModel() {
        VM = ViewModelProviders.of(this).get(MineFragmVM.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(View rootView) {
        rootView.setPadding(0, ScreenUtils.getStatusBarHeight(ShuaApplication.getContext()), 0, 0);
        vp = rootView.findViewById(R.id.vp);
        tabLayout = rootView.findViewById(R.id.tl);
        adapter = new MyPagerAdapter(getChildFragmentManager());
        imgAvatar = rootView.findViewById(R.id.imgAvatar);
        tvName = rootView.findViewById(R.id.tvName);
        imgEdit = rootView.findViewById(R.id.imgEdit);
        imgUnread = rootView.findViewById(R.id.imgUnread);
        tvFocus = rootView.findViewById(R.id.tvFocus);
        tvFans = rootView.findViewById(R.id.tvIsFocus);
        tvZan = rootView.findViewById(R.id.tvZan);
        tvSign = rootView.findViewById(R.id.tvSign);
        tvLogin = rootView.findViewById(R.id.tvLogin);
        tvLogin.setOnClickListener(this);
        llFocus = rootView.findViewById(R.id.llFocus);
        llFans = rootView.findViewById(R.id.llFans);
        llZan = rootView.findViewById(R.id.llZan);
        tvMyWing = rootView.findViewById(R.id.tvMyWing);
        tvMoney = rootView.findViewById(R.id.tvMoney);
        llWing = rootView.findViewById(R.id.llWing);
        llWallet = rootView.findViewById(R.id.llWallet);
        llNotice = rootView.findViewById(R.id.ll_notice);
        llNoticeClose = rootView.findViewById(R.id.ll_notice_close);
        tvNoticeOpen = rootView.findViewById(R.id.tv_notice_open);
        imgInviteFriends = rootView.findViewById(R.id.imgInvitationFriend);
        imgSetting = rootView.findViewById(R.id.imgSetting);
        bannerView = rootView.findViewById(R.id.banner_view);
//        ivPublish = rootView.findViewById(R.id.iv_publish);
        imgEdit.setOnClickListener(this);
        imgAvatar.setOnClickListener(this);
        llFocus.setOnClickListener(this);
        llFans.setOnClickListener(this);
        llZan.setOnClickListener(this);
        llWing.setOnClickListener(this);
        llWallet.setOnClickListener(this);
        imgSetting.setOnClickListener(this);
        llNoticeClose.setOnClickListener(this);
        tvNoticeOpen.setOnClickListener(this);
        rootView.findViewById(R.id.imgNotice).setOnClickListener(this);
        rootView.findViewById(R.id.imgKefu).setOnClickListener(this);
        rootView.findViewById(R.id.ll_loan).setOnClickListener(this);
        imgInviteFriends.setOnClickListener(this);
        fragments.add(MineLikeVideoFragment.newInstance(""));
        fragments.add(MineListVideoFragment.newInstance(""));
        vp.setAdapter(adapter);
        tabLayout.setViewPager(vp, titles);
        changeLogin();
        VM.getMe().observe(this, new Observer<Me>() {
            @Override
            public void onChanged(Me data) {
                if (data != null && data.isStatus() && data.getData() != null) {
                    setUI(data);
                }
            }
        });
//        registerLikeVideoReceiver();

//        ivPublish.setOnClickListener(v -> {
//            jumpToRecorder();
//        });
    }

    //    @Override
//    public void onRefreshing() {
//        super.onRefreshing();
//    }
    private void jumpToRecorder() {
        //TODO:录制相关
//        if (FastClickUtil.isFastClick()) {
//            return;
//        }
//        final AlivcRecordInputParam recordInputParam = new AlivcRecordInputParam.Builder()
//                .setResolutionMode(LittleVideoParamConfig.Recorder.RESOLUTION_MODE)
//                .setRatioMode(LittleVideoParamConfig.Recorder.RATIO_MODE)
//                .setMaxDuration(LittleVideoParamConfig.Recorder.MAX_DURATION)
//                .setMinDuration(LittleVideoParamConfig.Recorder.MIN_DURATION)
//                .setVideoQuality(LittleVideoParamConfig.Recorder.VIDEO_QUALITY)
//                .setGop(LittleVideoParamConfig.Recorder.GOP)
//                .setVideoCodec(LittleVideoParamConfig.Recorder.VIDEO_CODEC)
//                .setVideoRenderingMode(RenderingMode.Race)
//                .build();
//        AlivcSvideoRecordActivity.startRecord(mActivity, recordInputParam);
    }

    private void changeLogin() {
        if (Store.getInstance().isLogin()) {
            tvName.setVisibility(View.VISIBLE);
            tvSign.setVisibility(View.VISIBLE);
            tvLogin.setVisibility(View.GONE);
        } else {
            tvName.setVisibility(View.GONE);
            tvSign.setVisibility(View.GONE);
            tvLogin.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        changeLogin();
        requestData();
        setNoticeView();
    }

    private void setNoticeView() {
        if (hasNoticeClose) {
            return;
        }
        boolean isEnable = NotificationUtil.isNotifyEnabled(mActivity);
        llNotice.setVisibility(isEnable ? View.GONE : View.VISIBLE);
    }

//    @Override
//    public void onDestroy() {
//        if (likeVideoReceiver != null) {
//            BroadcastHandler.unregisterReceiver(getContext(), likeVideoReceiver);
//        }
//        super.onDestroy();
//    }

//    private void registerLikeVideoReceiver() {
//        BroadcastHandler.registerUpdateLikeVideoReceiver(ShuaApplication.getContext(), likeVideoReceiver);
//    }

//    private BroadcastReceiver likeVideoReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            refreshLikeVideo();
//        }
//    };

    private void requestData() {
        HttpData.getInstance().getUserBannerList(null, new ACallback<String>() {

            @Override
            public void onSuccess(String data) {
                if (!TextUtils.isEmpty(data) && bannerView.getAdapter() == null) {
                    List<BannerBean> bannerList = ParseJsonUtils.parseListData(data, "data", BannerBean.class);
                    if (!bannerList.isEmpty()) {
                        bannerView.setVisibility(View.VISIBLE);
                        Glide.with(getActivity())
                                .asBitmap()
                                .load(bannerList.get(0).banner_url)
                                .into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                        int height = bannerView.getLayoutParams().height = (int) ((float) UIUtils.getScreenWidthPx(getActivity()) / resource.getWidth() * resource.getHeight());
                                        fetchBanner(bannerView, height);
                                        bannerView.refreshData(bannerList);
                                    }
                                });
                    } else {
                        bannerView.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });


        if (!Store.getInstance().isLogin()) {
            return;
        }
        VM.getData();
        HttpData.getInstance().getWallet(new AbsCallback<BaseData<Wallet>>() {
            @Override
            public void onRealSuccess(BaseData<Wallet> data) {
                if (data.isStatus()) {
                    tvMoney.setText(data.getData().getBalance() + "");
                    tvMyWing.setText(data.getData().getPoint() + "");
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
        HttpData.getInstance().getNotificationInfo(new AbsCallback<BaseData<NotificationInfo>>() {
            @Override
            public void onRealSuccess(BaseData<NotificationInfo> data) {
                if (data != null && data.isStatus() && data.getData() != null) {
                    imgUnread.setVisibility(data.getData().hasUnread() ? View.VISIBLE : View.GONE);
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    private void fetchBanner(BannerViewPager bannerViewPager, int height) {
        bannerViewPager.setScrollDuration(600)
                .setIndicatorStyle(IndicatorStyle.CIRCLE)
                .setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
                .setInterval(3000)
                .setIndicatorGravity(IndicatorGravity.CENTER)
                .setIndicatorMargin(0, 10, 0, 0)
                .setAutoPlay(true)
                .setIndicatorSliderColor(getActivity().getResources().getColor(R.color.red_normal_color),
                        getActivity().getResources().getColor(R.color.red_checked_color))
                .setAdapter(new MineBannerAdapter(height, (url, title) -> {
                    if (!ToLogin()) {
                        reportAdvertAction(TrackConstants.ACTION_MY_SHOUTU, TrackConstants.NOTE_MY_SHOUTU);
                        if (url.startsWith("http")) {
                            startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", url).putExtra("title", title));
                        } else {
                            startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + url + "?token=" + ShuaApplication.accessToken).putExtra("title", title));
                        }
                    }
                }))
                .create();
    }

    private void refreshLikeVideo() {
//        if (likeVideoFragment != null) {
//            likeVideoFragment.onRefresh();
//        }
    }

    public void setUI(Me data) {
        Store.getInstance().setAgent_code(data.getData().getAgent_code() + "");
        Store.getInstance().setUserName(data.getData().getName());
//        Store.getInstance().setBingWx(data.getData().getIs_bind_wechat());

        tvName.setText(data.getData().getName());
        tvFocus.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getFollow_count()));
        tvFans.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getFans_count()));
        tvZan.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getPraise_count()));
        if (!TextUtils.isEmpty(data.getData().getSignature())) {
            tvSign.setText(data.getData().getSignature());
        }
        Glide.with(this).load(data.getData().getAvatar())
                .error(R.mipmap.ic_avatar_default)
                .placeholder(R.mipmap.ic_avatar_default)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))//圆形
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgAvatar);
        this.data = data.getData();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            changeLogin();
            requestData();
            setNoticeView();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FOCUSLISTACTIVITY || requestCode == EDITPERSONALACTIVITY) {
            if (resultCode == RESULT_OK) {
                requestData();
            }
        } else if (requestCode == CommonConstants.MAIN) {
            if (resultCode == RESULT_OK) {
                ((MainActivity) mActivity).openHome();
            }
        } else if (requestCode == WITHDRAW) {
            if (resultCode == RESULT_OK) {
                try {
                    String taskType = data.getStringExtra("taskType");
                    dealWithdrawResult(taskType);
                } catch (Exception e) {
                    ((MainActivity) mActivity).openHome();
                }
            }
        } else if (requestCode == CommonConstants.XITONGXIAOXI) {
            if (resultCode == RESULT_OK) {
                ((MainActivity) mActivity).openHome();
            }
        }
    }

    private void dealWithdrawResult(String taskType) {
        if (TextUtils.isEmpty(taskType)) {
            ((MainActivity) mActivity).openGift();
            ((MainActivity) mActivity).scrollToModle("theTaskMod");
            return;
        }
        if ("task".equals(taskType)) {
            ((MainActivity) mActivity).openGift();
            ((MainActivity) mActivity).scrollToModle("theTaskMod");
            return;
        }
        if ("friend".equals(taskType)) {
            jumpToFriend();
        } else if ("home".equals(taskType)) {
            ((MainActivity) mActivity).openHome();
        } else if ("game".equals(taskType)) {
            DyAdApi.getDyAdApi().jumpAdList(mActivity, Store.getInstance().getuserId(), 0);
            ;
        }
    }

    private void jumpToFriend() {
        if (!ToLogin()) {
            startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true));
        }
    }


    private boolean ToLogin() {
        if (!Store.getInstance().isLogin()) {
            startActivity(new Intent(getContext(), LoginActivity.class));
            return true;
        }
        return false;
    }


    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_MINE, action, note);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_notice_open:
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_PUSH_OPEN, TrackConstants.NOTE_MY_PUSH_OPEN);
                ToNotification.open(mActivity);
                break;
            case R.id.ll_notice_close:
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_PUSH_OFF, TrackConstants.NOTE_MY_PUSH_OFF);
                llNotice.setVisibility(View.GONE);
                hasNoticeClose = true;
                break;
            case R.id.imgNotice://消息
                if (!ToLogin()) {
                    startActivityForResult(new Intent(mActivity, MessageActivity.class), CommonConstants.XITONGXIAOXI);
                }
                break;
            case R.id.tvLogin:
                startActivity(new Intent(mActivity, LoginActivity.class));
                break;
            case R.id.imgAvatar:
            case R.id.imgEdit://编辑信息
                if (!ToLogin()) {
                    Intent intent = new Intent(mActivity, EditPersonalActivity.class);
                    intent.putExtra(EditPersonal, data);
                    startActivityForResult(intent, EDITPERSONALACTIVITY);
                }
                break;
            case R.id.llFocus://我的关注
                if (!ToLogin()) {
                    startActivityForResult(new Intent(mActivity, FocusListActivity.class).putExtra("FocusList", 0).putExtra("FocusList1", 1), FOCUSLISTACTIVITY);
                }
                break;
            case R.id.llFans://我的粉丝
                if (!ToLogin()) {
                    startActivityForResult(new Intent(mActivity, FocusListActivity.class).putExtra("FocusList", 1).putExtra("FocusList1", 0), FOCUSLISTACTIVITY);
                }
                break;
            case R.id.llZan://获赞数
                if (!ToLogin()) {
                    startActivity(new Intent(mActivity, ListVideoActivity.class));
                }
                break;
            case R.id.llWallet://当前余额
                if (!ToLogin()) {
                    reportAdvertAction(TrackConstants.ACTION_MY_TIXIAN, TrackConstants.NOTE_MY_TIXIAN);
                    startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), WITHDRAW);
                }
                break;
            case R.id.llWing://我的金豆
                if (!ToLogin()) {
                    reportAdvertAction(TrackConstants.ACTION_MY_WATTER, TrackConstants.NOTE_MY_WATTER);
                    startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "wallet?tabs=1" + "&token=" + ShuaApplication.accessToken).putExtra("title", "账户流水"), CommonConstants.MAIN);
                }
                break;
            case R.id.imgInvitationFriend://邀请好友
                if (!ToLogin()) {
                    reportAdvertAction(TrackConstants.ACTION_MY_SHOUTU, TrackConstants.NOTE_MY_SHOUTU);
                    startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn" + "?token=" + ShuaApplication.accessToken).putExtra("title", "邀请好友"));
                }
                break;
            case R.id.imgSetting://设置
                Intent intent1 = new Intent(mActivity, SettingActivity.class);
                intent1.putExtra(EditPersonal, data);
                startActivityForResult(intent1, SETTINGACTIVITY);
                break;
            case R.id.imgKefu://问题反馈
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_PROBLEM, TrackConstants.NOTE_MY_PROBLEM);
                if (!ToLogin()) {
                    startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "feedback").putExtra("title", "问题反馈"));
                }
                break;
            case R.id.ll_loan:
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_MONEY, TrackConstants.NOTE_MY_MONEY);
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", LOAN_URL), CommonConstants.MAIN);
                break;
        }

    }

}
